package com.swt.sendmsg;

import android.Manifest;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Process;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MainActivity extends Activity {
    private String message;
    private String number;
    private EditText editText;
    private EditText editText2;
    private ImageView back;
    private ImageView lxr;
    private static final int PICK_CONTACT = 0;
    public static int PERMISSION_REQ = 0x123456;
    public static int SEND_SMS_REQ = 0x223456;

    private String[] mPermission = new String[]{
            Manifest.permission.SEND_SMS,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.READ_CONTACTS
    };

    private List<String> mRequestPermission = new ArrayList<String>();


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = (EditText) this.findViewById(R.id.number);
        editText2 = (EditText) this.findViewById(R.id.message);
        back = (ImageView) this.findViewById(R.id.back);
        lxr = (ImageView) this.findViewById(R.id.lxr);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        lxr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mRequestPermission.clear();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    for (String one : mPermission) {
                        if (PackageManager.PERMISSION_GRANTED != MainActivity.this.checkPermission(one, Process.myPid(), Process.myUid())) {
                            mRequestPermission.add(one);
                        }
                    }
                    if (!mRequestPermission.isEmpty()) {
                        MainActivity.this.requestPermissions(mRequestPermission.toArray(new String[mRequestPermission.size()]), PERMISSION_REQ);
                        return;
                    }
                }
                goPick();

            }
        });

        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                number = editText.getText().toString();
                message = editText2.getText().toString();
                // 在LogCat中可以查看到number和message的相关信息 
                Log.i("number", number);
                Log.i("message", message);

                if (TextUtils.isEmpty(number)) {
                    Toast.makeText(MainActivity.this, "请输入联系人号码", Toast.LENGTH_LONG).show();
                    return;
                }
                if (!isMobileNO(number)) {
                    Toast.makeText(MainActivity.this, "请输入正确的手机号码", Toast.LENGTH_LONG).show();
                    return;
                }
                mRequestPermission.clear();
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                    for (String one : mPermission) {
                        if (PackageManager.PERMISSION_GRANTED != MainActivity.this.checkPermission(one, Process.myPid(), Process.myUid())) {
                            mRequestPermission.add(one);
                        }
                    }
                    if (!mRequestPermission.isEmpty()) {
                        MainActivity.this.requestPermissions(mRequestPermission.toArray(new String[mRequestPermission.size()]), SEND_SMS_REQ);
                        return;
                    }
                }
                send();

            }
        });

    }

    public void send() {
        /*获取系统默认的信息管理器，一定要注意的是SmsManager是android.telephony.SmsManager;这和
         *我们使用的版本有关，在 Android 2.0 以前 应该使用 android.telephony.gsm.SmsManager
         *Android 2.0 之后的版本应该用 android.telephony.SmsManager。
         */
        SmsManager smsManager = SmsManager.getDefault();
        /*PendingIntent.getBroadcast返回一个用于广播的PendingIntent对象，类似于调用Content.sendBroadcast();
         */
        PendingIntent paIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent("SMS_SENT2"), 0);
        PendingIntent deliveryIntent = PendingIntent.getBroadcast(MainActivity.this, 0, new Intent("SMS_DELIVERED2"), 0);


        // 注册一个BroadcastReceiver,当有匹配它的IntentFilter的Intent出现时，该方法会被触发
        registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                int resultCode = getResultCode();
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        Toast.makeText(MainActivity.this, "信息发送成功了哦", Toast.LENGTH_LONG).show();
                        Log.i("swt", "信息发送成功了哦");
                        editText.setText("");
                        editText2.setText("");
                        break;
                    default:
                        Toast.makeText(MainActivity.this, "信息发送失败了哦", Toast.LENGTH_LONG).show();
                        Log.i("swt", "信息发送失败了哦");

                }
            }


        }, new IntentFilter("SMS_SENT2"));


        registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(MainActivity.this, "短信已查收", Toast.LENGTH_LONG).show();
                Log.i("swt", "短信已查收");
                editText.setText("");
                editText2.setText("");
            }
        }, new IntentFilter("SMS_DELIVERED2"));


        // smsManager.divideMessage有些时候短信如果超过了字数，我们就需要这个方法来帮我们拆分短信内容。
        ArrayList<String> smses = smsManager.divideMessage(message);
        Iterator<String> iterator = smses.iterator();
        while (iterator.hasNext()) {
            String temp = iterator.next();
            //发送短信
            smsManager.sendTextMessage(number, null, temp, paIntent, deliveryIntent);
        }
        // 弹出一个浮动框显示提示内容，Toast.LENGTH_LONG代表浮动框显示时间的长短
        Toast.makeText(MainActivity.this, "短信发送完成", Toast.LENGTH_LONG).show();
        Log.i("swt", "短信发送完成");
        editText.setText("");
        editText2.setText("");
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // 版本兼容
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
            return;
        }
        if (requestCode == PERMISSION_REQ) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[0] == -1) {
                    Toast.makeText(MainActivity.this, "请开启权限", Toast.LENGTH_LONG).show();
                    return;
                }
                for (String one : mPermission) {
                    if (permissions[i].equals(one) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        mRequestPermission.remove(one);
                    }
                }
            }
            goPick();
        }
        if (requestCode == SEND_SMS_REQ) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[0] == -1) {
                    Toast.makeText(MainActivity.this, "请开启权限", Toast.LENGTH_LONG).show();
                    return;
                }
                for (String one : mPermission) {
                    if (permissions[i].equals(one) && grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        mRequestPermission.remove(one);
                    }
                }
            }
            send();
        }
    }

    public void goPick() {
        if (mRequestPermission.isEmpty()) {

            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, PICK_CONTACT);

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case PICK_CONTACT:
                if (data == null) {
                    return;
                }
                //处理返回的data,获取选择的联系人信息
                Uri uri = data.getData();
                String[] contacts = getPhoneContacts(uri);
//               et_name.setText(contacts[0]);
                editText.setText(contacts[1].replaceAll(" ",""));
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private String[] getPhoneContacts(Uri uri) {
        String[] contact = new String[2];
        //得到ContentResolver对象
        ContentResolver cr = getContentResolver();
        //取得电话本中开始一项的光标
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;

    }

    /**
     * 验证手机格式
     */
    public boolean isMobileNO(String number) {
    /*
    移动：134、135、136、137、138、139、150、151、152、157(TD)、158、159、178(新)、182、184、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、170、173、177、180、181、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String num = "[1][34578]\\d{9}";//"[1]"代表第1位为数字1，"[34578]"代表第二位可以为3、4、5、7、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(number)) {
            return false;
        } else {
            //matches():字符串是否在给定的正则表达式匹配
            return number.matches(num);
        }
    }
}

